<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="140px">
      <!--      <el-form-item label="设备id" prop="deviceId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.deviceId"-->
      <!--          placeholder="请输入设备id"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="设备名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />

      </el-form-item>
      <!--      <el-form-item label="mqtt推送的主题" prop="pushTopic">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.pushTopic"-->
      <!--          placeholder="请输入mqtt推送的主题"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="mqtt接收的主题" prop="subTopic">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.subTopic"-->
      <!--          placeholder="请输入mqtt接收的主题"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="是否在线" prop="isOnline">
        <el-select v-model="queryParams.isOnline" placeholder="是否在线" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备分类" prop="category">
        <el-select v-model="queryParams.category" placeholder="设备分类" clearable>
          <el-option
            v-for="dict in categoryList"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" style="margin-top: 20px;">
      <el-col :xs="24" :sm="24" :md="6" :lg="4" v-hasPermi="['system:device:add']">
        <div class="device-list addBox-line" @click="handleAdd">
          <i class="el-icon-plus"></i>
          <span>新增设备</span>
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :md="6" :lg="4" v-for="(item,index) in deviceList" :key="index">
        <div class="device-list">
          <div class="device-list-title" @click="detailId=item.id,showDetail=true"><img :src=item.pic
                                                                                        @error="itemError(item)" alt="">{{
              item.name
            }}
          </div>
          <div class="device-list-num" @click="detailId=item.id,showDetail=true">
            <div class="device-list-num-l">
              <!--              <el-switch-->
              <!--                v-model="item.isOnline"-->
              <!--                active-text="在线"-->
              <!--                active-color="#13ce66"-->
              <!--                inactive-color="#ff4949"-->
              <!--                inactive-text="离线"-->
              <!--                :active-value="0"-->
              <!--                :inactive-value="1"-->
              <!--              >-->
              <!--              </el-switch>-->
              <!--              <p class="device-detail-samllTitle">4mouths a go</p>-->
            </div>
          </div>
          <div class="device-list-footer">
            <span class="el-icon-edit" @click="handleUpdate(item)"></span>
            <span class="el-icon-delete" @click="handleDelete(item)"></span>
          </div>
        </div>
      </el-col>
    </el-row>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <boxDetail :visible.sync="showDetail" :detailId="detailId"></boxDetail>

    <!-- 添加或edit设备管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body custom-class="device-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-row :gutter="10" style="margin-top: 20px;">
          <el-col :xs="24" :sm="24" :md="12" :lg="12">
            <el-form-item label="设备ID" prop="deviceId">
              <el-input v-model="form.deviceId" placeholder="设备ID"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12">
            <el-form-item label="设备名称" prop="name">
              <el-input v-model="form.name" placeholder="设备名称"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12">
            <el-form-item label="Mqtt推送" prop="pushTopic">
              <!--              {{ form.pushTopic || '选择所属类目' }}-->
              <div style="display: flex;">
                <el-input
                  v-model="form.pushTopic"
                  placeholder="Mqtt推送"
                  clearable
                />
                <el-button class="button-line" @click="roleUp('pushTopic')">默认</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12">
            <el-form-item label="Mqtt接收" prop="subTopic">
              <!--              {{ form.subTopic || '选择所属类目' }}-->
              <div style="display: flex;">
                <el-input
                  v-model="form.subTopic"
                  placeholder="Mqtt接收"
                  clearable
                />
                <el-button class="button-line" @click="roleUp('subTopic')">默认</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12">
            <el-form-item label="是否在线" prop="isOnline">
              <el-radio-group v-model="form.isOnline">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12">
            <el-form-item label="所属部门" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="所属部门"/>
            </el-form-item>
          </el-col>
          <!--          <el-col :xs="24" :sm="24" :md="24" :lg="24">-->
          <!--            <el-form-item label="图片" prop="pic">-->
          <!--              <image-upload v-model="form.pic"/>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="设备类目" prop="category">
              <el-select v-model="form.category" placeholder="设备类目"
                         :disabled="form.id?true:false" @change="getCateList()">
                <el-option
                  v-for="dict in categoryList"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div v-if="!form.id">
          <el-divider content-position="center">基本规则</el-divider>
          <el-table :data="rulesList"
                    ref="multipleTable"
                    @row-click="rowClick"
                    @selection-change="handleCateSelectionChange">
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column label="ID" prop="id" width="80"/>
            <el-table-column label="规则名称" prop="name"/>
            <el-table-column label="开始时间" prop="beginTime"/>
            <el-table-column label="结束时间" prop="endTime"/>
          </el-table>
        </div>
        <el-divider content-position="center">组件信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddComponent">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteComponent">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="componentList" :row-class-name="rowComponentIndex"
                  @selection-change="handleComponentSelectionChange" ref="component">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="序列号" align="center" prop="index" width="50"/>
          <el-table-column label="名称" prop="componentName">
            <template slot-scope="scope">
              <el-input v-model="scope.row.componentName" placeholder="名称"/>
            </template>
          </el-table-column>
          <el-table-column label="字段" prop="columnName" width="110">
            <template slot-scope="scope">
              <el-input v-model="scope.row.columnName" placeholder="字段"/>
            </template>
          </el-table-column>
          <el-table-column label="值" prop="columnValue" width="110">
            <template slot-scope="scope">
              <el-input v-model="scope.row.columnValue" placeholder="值"/>
            </template>
          </el-table-column>
          <el-table-column label="开启" prop="isDisjunctor" width="190">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.isDisjunctor"
                active-text="是"
                active-color="#13ce66"
                inactive-color="#ff4949"
                inactive-text="否"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确认</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import boxDetail from "./components/boxDetail";
import {listDevice, getDevice, delDevice, addDevice, updateDevice} from "@/api/system/device";
import {categorycommandlist, devicecommand} from "@/api/system/command"
import {deptTreeSelect} from "@/api/system/user";
import {listCategory} from "@/api/system/category";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listRules} from "@/api/system/rules";
import {addRules} from "@/api/system/rules";

export default {
  name: "User",
  dicts: ['sys_normal_disable'],
  components: {boxDetail, Treeselect},
  data() {
    return {
      detailId: 0,
      showDetail: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedComponent: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示search条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备管理表格数据
      deviceList: [],
      // 设备分类数据
      categoryList: [],
      // 元器件表格数据
      componentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceId: null,
        pushTopic: null,
        subTopic: null,
        isOnline: null
      },
      // 表单参数
      form: {},
      // 部门树选项
      deptOptions: undefined,
      // 表单校验
      rules: {
        deviceId: [
          {required: true, message: "设备id不能为空", trigger: "blur"}
        ],
        name: [
          {required: true, message: "设备名称不能为空", trigger: "blur"}
        ],
        category: [
          {required: true, message: "设备分类不能为空", trigger: "blur"}
        ],
        pushTopic: [
          {required: true, message: "mqtt推送的主题不能为空", trigger: "blur"}
        ],
        subTopic: [
          {required: true, message: "mqtt接收的主题不能为空", trigger: "blur"}
        ],
        createTime: [
          {required: true, message: "创建时间不能为空", trigger: "blur"}
        ],
        isOnline: [
          {required: true, message: "是否在线不能为空", trigger: "change"}
        ],
        deptId: [
          {required: true, message: "归属部门不能为空", trigger: "change"}
        ]
      },
      rulesList: [],
      multipleSelection: [],
      multipleSelectionList: [],
      keyCommandList: []
    };
  },
  watch: {},
  created() {
    this.getList();
    this.getCategoryList();
    this.getDeptTree()
  },
  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    getCategoryList() {
      this.loading = true;
      listCategory().then(response => {
        this.categoryList = response.rows;
        this.loading = false;
      });
    },
    /** 查询设备管理列表 */
    getList() {
      this.loading = true;
      listDevice(this.queryParams).then(response => {
        this.deviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // cancel按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单reset
    reset() {
      this.form = {
        id: null,
        deviceId: null,
        name: null,
        pushTopic: null,
        subTopic: null,
        createTime: null,
        isOnline: 0,
        category: null,
        pic: null,
        deptId: null
      };
      this.componentList = [];
      this.rulesList = []
      this.resetForm("form");
    },
    /** search按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** reset按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** add按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增设备";
    },
    /** edit按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDevice(id).then(response => {
        this.form = response.data;
        this.componentList = response.data.componentList;
        this.roleUp()
        this.open = true;
        this.title = "编辑设备";
        this.getSwitch()
      });
    },
    /** 提交按钮 */
    submitForm() {
      let data_ = JSON.parse(JSON.stringify(this.form))
      this.$refs["form"].validate(valid => {
        if (valid) {
          data_.componentList = this.componentList;
          if (data_.id != null) {
            delete data_.lastUpTime
            delete data_.lastDownTime
            // console.log('提交的数据：', data_)
            // let state = 1
            // if (state) {
            //   return
            // }
            updateDevice(data_).then(response => {
              this.$modal.msgSuccess("edit成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDevice(data_).then(response => {
              console.log('设备信息：', response)
              // this.$modal.msgSuccess("add成功");
              // this.open = false;
              // this.getList();
              this.addNewRuleFn(0, response.data)
            });
          }
        }
      });
    },
    /** delete按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认delete【' + row.name + '】设备的数据项？').then(function () {
        return delDevice(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("delete成功");
      }).catch(() => {
      });
    },
    /** 元器件序号 */
    rowComponentIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 元器件添加按钮操作 */
    handleAddComponent() {
      let obj = {};
      obj.componentName = "";
      obj.columnName = "";
      obj.columnValue = "";
      obj.isDisjunctor = "";
      this.componentList.push(obj);
    },
    /** 元器件delete按钮操作 */
    handleDeleteComponent() {
      if (this.checkedComponent.length == 0) {
        this.$modal.msgError("请先选择要delete的元器件数据");
      } else {
        const componentList = this.componentList;
        const checkedComponent = this.checkedComponent;
        this.componentList = componentList.filter(function (item) {
          return checkedComponent.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleComponentSelectionChange(selection) {
      this.checkedComponent = selection.map(item => item.index)
    },
    itemError(item) {
      item.pic = require('@/assets/images/Icon.png')
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/device/export', {
        ...this.queryParams
      }, `device_${new Date().getTime()}.xlsx`)
    },
    roleUp(option) {
      //
      // pushTopic 推送规则 subTopic 接收规则
      console.log('option:', option, this.form)
      if(!this.form.category){
        this.$message.error('选择类目')
        return
      }
      for (let item of this.categoryList) {
        if (this.form.category === item.id) {
          if (item[option]) {
            this.form[option] = item[option].replace("{deviceId}", this.form.deviceId || '设备id')
          } else {
            this.form[option] = ''
          }
        }
      }
      // if (option !== 'input' && !this.form.id) {
      //   this.getCateList()
      //   this.getSwitch()
      // }
    },
    // 类目默认规则
    getCateList() {
      let n = this
      this.rulesList = []
      listRules({
        pageNum: 1,
        pageSize: 100,
        cateId: this.form.category,
        type: 1,
      }).then(response => {
        n.rulesList = response.rows;
        this.$nextTick(() => {
          for (let i in n.rulesList) {
            this.multipleSelection.push(n.rulesList[i].id)
            n.$refs.multipleTable.toggleRowSelection(n.rulesList[i], true)
          }
        })
      });
      this.getSwitch()
    },
    handleCateSelectionChange(val) {
      this.multipleSelectionList = JSON.parse(JSON.stringify(val))
    },
    rowClick(row) {
      let n = this
      if (this.multipleSelection.indexOf(row.id) === -1) {
        this.multipleSelection.push(row.id)
      } else {
        this.multipleSelection.splice(this.multipleSelection.indexOf(row.id), 1)
      }
      for (let i in n.rulesList) {
        let item = n.rulesList[i]
        if (item.id === row.id) {
          if (n.multipleSelection.indexOf(item.id) !== -1) {
            n.$refs.multipleTable.toggleRowSelection(n.rulesList[i], true)
          } else {
            n.$refs.multipleTable.toggleRowSelection(n.rulesList[i], false)
          }
        }
      }
    },
    // 新设备添加默认的规则
    addNewRuleFn(index, deviceId) {
      console.log('multipleSelectionList:', this.multipleSelectionList)
      if(this.multipleSelectionList.length){
        let n = this
        let list_ = JSON.parse(JSON.stringify(this.multipleSelectionList))
        let data_ = {
          name: list_[index].name,
          cateId: 0, // 分类id
          type: 2, // 1分类2设备
          andCondition: list_[index].andCondition || '', // and 数据
          orCondition: list_[index].orCondition || '', // or 数据
          allCondition: list_[index].allCondition, // 前端自定义数据
          beginTime: list_[index].beginTime, // 规则开始时间
          endTime: list_[index].endTime, // 规则结束时间
          commandId: list_[index].commandId,
          deviceId: deviceId,
          isAlarm: list_[index].isAlarm,//  是否告警
          alarmNumber: list_[index].alarmNumber // 每日告警数
        }
        if (!data_.andCondition) {
          delete data_.andCondition
        }
        if (!data_.orCondition) {
          delete data_.orCondition
        }
        console.log('data_:', data_)
        addRules(data_).then(res => {
          let index_ = index + 1
          if (index_ < this.multipleSelectionList.length) {
            n.addNewRuleFn(index + 1, deviceId)
          } else {
            // this.$modal.msgSuccess("add成功");
            // this.open = false;
            // this.getList();
            this.AddDevicecommand(0, deviceId, JSON.parse(JSON.stringify(n.keyCommandList)))
          }
        })
      }
    },
    // 获取类目中的默认操作命令
    getSwitch() {
      categorycommandlist({cateId: this.form.category}).then(res => {
        console.log('类目默认开关指令：', res)
        this.keyCommandList = JSON.parse(JSON.stringify(res.rows))
      })
    },
    // 添加单个设备的指令
    AddDevicecommand(index, deviceId, list) {
      let n = this
      let data_ = {
        deviceId: deviceId, //  设备id
        sku: list[index].sku, //   属性名
        value: list[index].value, // 属性值
        command: list[index].command, //  命令
      }
      devicecommand(data_).then(res => {
        console.log('res设备指令:', res)
        let index_ = index + 1
        if (index_ < this.keyCommandList.length) {
          n.AddDevicecommand(index_, deviceId, list)
        } else {
          this.$modal.msgSuccess("add成功");
          this.open = false;
          this.getList();
        }
      })
    }
  }
};
</script>
<style>
.device-list {
  box-shadow: 0 2px 2px #ddd;
  border: 1px solid #ddd;
  border-radius: 5px;
  box-sizing: border-box;
  margin-bottom: 10px;
}

.device-list-title {
  display: flex;
  align-items: center;
  padding: 20px 0 10px 20px;
  cursor: pointer;
}

.device-detail-samllTitle {
  color: rgb(116, 121, 140);
  font-size: 14px;
}

.device-list-title img {
  margin-right: 10px;
}

.device-list-footer {
  border-top: 1px solid #eee;
  padding: 10px 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.device-list-footer span {
  display: block;
  font-size: 18px;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: #eee;
  color: #9ca2aa;
  line-height: 30px;
  text-align: center;
  margin-right: 10px;
  cursor: pointer;
}

.device-list-footer span:last-child {
  margin-right: 0;
}

.device-list-num {
  display: flex;
  height: 85px;
  align-items: center;
}

.device-list-num-l {
  flex: 1;
  text-align: center;
}

.device-list-num-l p:first-child {
  color: rgba(116, 121, 140, 1)
}

.addBox-line {
  height: 192px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  cursor: pointer;
}

.addBox-line i {
  font-size: 20px;
  height: 45px;
  width: 45px;
  text-align: center;
  line-height: 45px;
  margin-bottom: 13px;
  background: #eee;
  font-weight: bold;
  border-radius: 50%;
}

.addBox-line span {

}
.button-line{
  margin-left:10px;
}
</style>
